//路由模块
const express = require('express')
const request = require('request')
// 创建路由对象
const router = express.Router()
// const db = require('../mysql_module/index')
// 1. 导入 mysql 模块
const mysql = require('mysql')
// 2. 建立与 MySQL 数据库的连接关系
const db = mysql.createPool({
    multipleStatements: true,
    host: '*.*.*.*', // 数据库的 IP 地址
    port: '3306',
    user: 'server_test', // 登录数据库的账号
    password: 'lzf749882178', // 登录数据库的密码
    database: 'server_test' // 指定要操作哪个数据库
})
const  createToken = require('../util/authorization')

let timestamp = new Date().getTime()


// 查询用户积分记录
router.post('/userRecord', (req,  res) =>{
    let userRecord = `select * from integral where userId = '${req.body.userId}'`
    db.query(userRecord, (err, results) =>{
        if (err) {
            res.send({
                msg: 'err',
                code: -1,
                timestamp
            })
            return
        }
        res.send({
            data: results,
            msg: 'ok',
            code: 200,
            timestamp
        })
    })
})


// 微信登录
router.post('/loginCode', (req, res) => {
    let jscode2session = `https://api.weixin.qq.com/sns/jscode2session?appid=wx12c5da28075ff30f&secret=818d239ee57cdcd048830227c7b53e5b&js_code=${req.query.code}&grant_type=authorization_code`
    request(jscode2session, (err, results, body) =>{
        // console.log(req, res, body)
        res.send({
            data: {
                msg: 'ok',
                code: 200
            },
            timestamp
        })
    })
})

//用户信息
router.post('/user', (req, res) => {
    let selectUserInfo  = `SELECT * FROM user WHERE phone = ${req.body.phone}`
    db.query(selectUserInfo, (err, results) => {
        if (err) {
            res.send({
                msg: 'err',
                code: -1,
                timestamp
            })
            return
        }
        res.send({
            data: results[0],
            msg: 'ok',
            code: 200,
            timestamp
        })
    })

})

// 用户登录
router.post('/userLogin', (req, res) => {
    timestamp = new Date().getTime()
    let selectUserInfo  = `SELECT * FROM user WHERE phone = ${req.body.phone}`
    db.query(selectUserInfo, (err, results) => {
        if (err || !results.length) {
            res.send({
                // data: {
                msg: '账号或密码错误',
                code: -1,
                timestamp
            })
            return
        }
        if (results[0].phone == req.body.phone && results[0].password == req.body.password) {
            res.send({
                data: {
                    ...results[0],
                    token: createToken.createToken()
                },
                msg: 'ok',
                code: 200,
                timestamp
            })
        } else  {
            res.send({
                data: {
                    msg: '账号或密码错误',
                    code: -1
                },
                timestamp
            })
        }

    })
})


// 用户注册
router.post('/logonIn', (req, res) => {
    console.log(req.body)
    let selectOldUserId = `select userId from user order by id desc limit 1;`
    db.query(selectOldUserId, (err, results) => {
        let oldUserId = 1000
        if (results.length) {
            oldUserId = Number(results[0].userId) + 1
        }

        let addUser = `INSERT INTO user (userId, phone, password, createTime) VALUES (${oldUserId}, ${req.body.phone}, ${req.body.password}, Now())`
        db.query(addUser, (err, results) => {
            if (err) {
                res.send({
                    // data:
                    msg: '该号码已存在',
                    code: err.errno,
                    timestamp
                })
                return
            } else  {
                res.send({
                    // data:
                    msg: 'ok',
                    code: 200,
                    timestamp
                })
            }
        })
    })

})

// 向外导出路由对象
module.exports = router